import React, { useEffect, useState } from 'react';
import { isFunction } from 'lodash';

import { defaultFormatResult } from '@/hooks';
import { orgService } from '@/services/salaryManage/orgService';

import { CACHE, loadingCache } from './cache';

const deepTransform = (data = []) =>
    data.map(({ positionName, positionCode, children = [], deleteFlag }) => ({
        value: positionCode,
        title: <div>
            { positionName }
            <span style={{ color: 'red' }}>{deleteFlag === 1 ? '（已删除）' : ''}</span>
        </div>,
        filterProp: positionName,
        key: positionCode,
        children: children.length > 0 ? deepTransform(children) : children
    }));

const useGradeList = (dataSource, cacheKey) => {
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState([]);

    useEffect(() => {
        let requestPromise;

        if (cacheKey && CACHE.get(cacheKey)) {
            // 存在缓存时
            requestPromise = CACHE.get(cacheKey);
        } else if (cacheKey && loadingCache.get(cacheKey)) {
            // 正在加载时
            requestPromise = loadingCache.get(cacheKey);
        } else if (dataSource) {
            // 有数据时
            requestPromise = isFunction(dataSource) ? dataSource() : dataSource;
        } else {
            requestPromise = orgService.queryPostList();
        }

        if (cacheKey && !loadingCache.get(cacheKey)) {
            loadingCache.add(cacheKey, requestPromise);
        }

        setLoading(true);
        Promise.all([requestPromise])
            .then(([res]) =>
                res.hasOwnProperty('code') && res.hasOwnProperty('msg')
                    ? defaultFormatResult.formatResult(res)
                    : res
            )
            .then(response => {
                setData(deepTransform((response)));
                if (cacheKey) {
                    // 从待加载缓存中移除
                    loadingCache.remove(cacheKey);
                    // 添加到缓存
                    CACHE.add(cacheKey, response);
                }
            })
            .finally(() => setLoading(false));
    }, []);

    return [loading, data];
};

export default useGradeList;
